package menu

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/enum/common"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMenuLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMenuLogic {
	return &CreateMenuLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateMenuLogic) CreateMenu(in *backend.MenuInfo) (*backend.BaseIDResp, error) {
	// get parent level
	var menuLevel uint8
	if in.ParentId != nil && *in.ParentId != common.DefaultParentId {
		m, err := l.svcCtx.SysMenu.FindOne(l.ctx, *in.ParentId)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		menuLevel = m.MenuLevel + 1
	} else {
		menuLevel = 1
	}

	var menu model.SysMenu
	menu.MenuLevel = menuLevel
	if in.ParentId != nil {
		menu.ParentID = *in.ParentId
	}
	if in.Type != nil {
		menu.MenuType = uint8(*in.Type)
	}
	if in.Sort != nil {
		menu.Sort = uint16(*in.Sort)
	}
	if in.Path != nil {
		menu.Path = strings.TrimSpace(*in.Path)
	}
	if in.Name != nil {
		menu.Name = strings.TrimSpace(*in.Name)
	}
	if in.Redirect != nil {
		menu.Redirect = strings.TrimSpace(*in.Redirect)
	}
	if in.Component != nil {
		menu.Component = strings.TrimSpace(*in.Component)
	}
	if in.Status != nil {
		menu.Status = uint8(*in.Status)
	}
	if in.Meta != nil {
		if in.Meta.Title != nil {
			menu.Title = strings.TrimSpace(*in.Meta.Title)
		}
		if in.Meta.Icon != nil {
			menu.Icon = strings.TrimSpace(*in.Meta.Icon)
		}
		if in.Meta.HideMenu != nil {
			menu.HideMenu = uint8(*in.Meta.HideMenu)
		}
		if in.Meta.HideBreadcrumb != nil {
			menu.HideBreadcrumb = uint8(*in.Meta.HideBreadcrumb)
		}
		if in.Meta.HideTab != nil {
			menu.HideTab = uint8(*in.Meta.HideTab)
		}
		if in.Meta.HideChildrenInMenu != nil {
			menu.HideChildrenInMenu = uint8(*in.Meta.HideChildrenInMenu)
		}
		if in.Meta.IgnoreKeepAlive != nil {
			menu.IgnoreKeepAlive = uint8(*in.Meta.IgnoreKeepAlive)
		}
		if in.Meta.Affix != nil {
			menu.Affix = uint8(*in.Meta.Affix)
		}
		if in.Meta.FrameSrc != nil {
			menu.FrameSRC = strings.TrimSpace(*in.Meta.FrameSrc)
		}
		if in.Meta.CarryParam != nil {
			menu.CarryParam = uint8(*in.Meta.CarryParam)
		}
		if in.Meta.DynamicLevel != nil {
			menu.DynamicLevel = uint8(*in.Meta.DynamicLevel)
		}
		if in.Meta.RealPath != nil {
			menu.RealPath = strings.TrimSpace(*in.Meta.RealPath)
		}
	}
	now := time.Now()
	menu.CreatedAt = now
	menu.UpdatedAt = now
	err := l.svcCtx.SysMenu.Insert(l.ctx, nil, &menu)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseIDResp{
		Id:  menu.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
